<template>
  <n-modal
    ref="$modal"
    preset="dialog"
    v-model:show="visable"
    v-bind="$attrs"
    :draggable="true"
    :closable="false"
    :close-on-esc="false"
    :mask-closable="false"
    :style="{ width: '800px' }"
    @close="doClose"
  >
    <template #header>
      <div class="w-full cursor-move" id="basic-modal-bar">{{ title }}</div>
    </template>
    <template #default>
      <slot name="default"></slot>
    </template>
    <template #action v-if="!$slots.action">
      <n-space>
        <n-button type="primary" :loading="btnLoading" @click="doSave">{{
          saveBtnText
        }}</n-button>
        <n-button @click="doCancel">取 消</n-button>
      </n-space>
    </template>
    <template v-else #action>
      <slot name="action"></slot>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { NModal, useMessage } from "naive-ui";
import type { PModalMethods, PModalProps } from "./typing";

const $message = useMessage();
const props = withDefaults(defineProps<PModalProps>(), {
  closable: false,
  show: false,
  preset: "dialog",
  title: "操作",
  saveBtnText: "保 存",
});

const $modal = ref(null);
const btnLoading = ref(false);
const visable = ref(false);

const doSave = async () => {
  btnLoading.value = true;
  try {
    if (props.onSave) {
      const res = await props.onSave();
      if (res) {
        doClose();
      }
    }
  } catch (e) {
    console.error(e);
    $message.error("操作失败, 详情F12请查看控制台日志");
  } finally {
    btnLoading.value = false;
  }
};

const doClose = () => {
  visable.value = false;
  btnLoading.value = false;
};

const doCancel = async () => {
  try {
    if (props.onClose) {
      const res = await props.onClose();
      if (res) {
        doClose();
      }
    } else {
      doClose();
    }
  } catch (e) {
    console.error(e);
    $message.error("取消失败, 详情F12请查看控制台日志");
  }
};

const open = () => {
  btnLoading.value = false;
  visable.value = true;
};

const close = () => {
  visable.value = false;
  btnLoading.value = false;
};

defineExpose<PModalMethods>({
  open,
  close,
});
</script>
